require "starframe/eventable"

module StarFrame
  class Scene
    include StarFrame::Eventable
    
    # StarRuby::Game.run内で呼ぶこと
    # StarRuby::Game.run外で呼びたい場合はScene.to_procを使うこと
    def initialize game, *args
      @game   = game
      @screen = game.screen
      @running = true
      
      call_init *args
    end
    
    def call
      catch :exit_scene do
        call_update
        
        @screen.clear
        call_render
        
        true
      end
    end
    
    def start
      catch :exit_scene do
        loop do
          if @game.window_closing?
            call_quit
            return nil
          end
          
          @game.wait
          @game.update_state
          return @next_scene unless call
          @game.update_screen
        end
      end
    end
    
    private
    def render_texture *args
      @screen.render_texture *args
    end
    
    def exit_scene
      call_quit
      @next_scene = nil
      throw :exit_scene, false
    end
    
    def next_scene next_scene
      call_quit
      @next_scene = next_scene
      throw :exit_scene, false
    end
  end
end
